package com.javashizhan.demo.redissession.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.OncePerRequestFilter;

import com.javashizhan.demo.redissession.common.Constants;

/**
 * 
 * @Description: Session验证过滤器，如果没有登陆则跳转到错误界面
 *
 * @author 飞流
 * @date 2019年8月11日
 * @知识星球 Java实战营
 * @微信公众号 JAVA栈实战营
 * @站点 http://javashizhan.com/
 *
 */
@Configuration
public class SessionFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {

		if (isNeedAuth(request)) {
			Object userIdObject = request.getSession().getAttribute(Constants.SESSION_USER_ID);
			if (null == userIdObject) {
				response.sendRedirect("/errorPage");
			}
		}

		filterChain.doFilter(request, response);
	}

	/**
	 * 判断页面是否需要seesion鉴权
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ServletException
	 */
	private boolean isNeedAuth(HttpServletRequest request) throws IOException, ServletException {
		String uri = request.getRequestURI();
		String[] passUrlArr = new String[] { "/login", "removeSession", "/errorPage", "swagger", "api-docs" };
		for (int i = 0; i < passUrlArr.length; i++) {
			if (uri.indexOf(passUrlArr[i]) > -1) {
				return false;
			}
		}

		System.out.println(uri);

		return true;
	}
}
